
import React, { useEffect,useContext,useReducer } from 'react'
import axios from 'axios'
import './css/index.css'

// 减少组件层级,useContext==>实现步骤
// 1. 使用createContext 创建Context对象
// 2. 在顶层组件通过Provider 提供数据
// 3. 在底层组件通过useContext函数获取数据
let context = React.createContext()

export default function App() {
    const intialState={
        info:"",
        films:[]
    }
    const reducer=(prevState,action)=>{
        let newState={...prevState}
        switch(action.type){
            case "change-films":
                newState.films = action.value
                return newState
            case "change-info":
                newState.info = action.value
                return newState
            default:
                return prevState
        }
    }
    const[state,dispatch] =useReducer(reducer,intialState)
    // const [info, setinfo] = useState("")
    // const [films, setfilms] = useState([])
    useEffect(() => {
        axios.get('/test.json').then(res => {
            // setfilms(res.data.data.films)
            dispatch({
                type:"change-films",
                value:res.data.data.films
            })
        })
    }, [])
    return (
        // 2. 在顶层组件通过Provider 提供数据
        <context.Provider value={{
            state,dispatch
        }}>
            <div>
                {
                    state.films.map(item =>
                        <Films key={item.filmId} {...item} />
                    )
                }
                <FilmsDetail />
            </div>
        </context.Provider>
    )
}

function Films(props) {
    // 3. 在底层组件通过useContext函数获取数据
    const {dispatch} = useContext(context)

    let { name, poster, synopsis } = props
    return (

        <div>
            <img src={poster} alt={name} onClick={() => {
                dispatch({
                    type:"change-info",
                    value:synopsis
                })
            }} />
            {name}
        </div>

    )
}
function FilmsDetail() {
    // 3. 在底层组件通过useContext函数获取数据
    const {state} = useContext(context)
    return (

        <div className='filmsDetail'>
            {state.info ? state.info : "FilmsDetail"}
        </div>
    )
}

